import { ElMessage } from 'element-plus';

// 通知音效
const notificationSounds = {
    message: new Audio('/sounds/message.mp3'),
    notification: new Audio('/sounds/notification.mp3')
};

// 用户设置
interface NotificationSettings {
    muteNotifications: boolean; // 免打扰模式
    muteSounds: boolean; // 静音模式
}

// 初始化设置
const defaultSettings: NotificationSettings = {
    muteNotifications: false,
    muteSounds: false
};

// 存储用户设置
let userSettings: NotificationSettings = { ...defaultSettings };

/**
 * 初始化通知设置
 * @param settings 用户设置
 */
export function initNotificationSettings(settings: Partial<NotificationSettings>) {
    userSettings = { ...defaultSettings, ...settings };

    // 从localStorage读取设置
    try {
        const savedSettings = localStorage.getItem('notificationSettings');
        if (savedSettings) {
            userSettings = { ...userSettings, ...JSON.parse(savedSettings) };
        }
    } catch (error) {
        console.error('Failed to load notification settings:', error);
    }
}

/**
 * 更新通知设置
 * @param settings 要更新的设置
 */
export function updateNotificationSettings(settings: Partial<NotificationSettings>) {
    userSettings = { ...userSettings, ...settings };

    // 保存到localStorage
    try {
        localStorage.setItem('notificationSettings', JSON.stringify(userSettings));
    } catch (error) {
        console.error('Failed to save notification settings:', error);
    }
}

/**
 * 获取当前通知设置
 */
export function getNotificationSettings(): NotificationSettings {
    return { ...userSettings };
}

/**
 * 显示消息通知
 * @param title 通知标题
 * @param message 通知内容
 * @param type 通知类型
 */
export function showNotification(title: string, message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') {
    // 如果在免打扰模式下，不显示通知
    if (userSettings.muteNotifications) {
        return;
    }

    // 检查浏览器通知权限
    if (Notification && Notification.permission === 'granted') {
        const notification = new Notification(title, {
            body: message,
            icon: '/favicon.ico'
        });

        // 点击通知时的操作
        notification.onclick = () => {
            window.focus();
            notification.close();
        };

        // 播放声音
        playNotificationSound('notification');
    }
    // 如果没有通知权限，使用Element Plus的消息提示
    else {
        ElMessage({
            message,
            type,
            duration: 3000
        });

        // 播放声音
        playNotificationSound('notification');
    }
}

/**
 * 显示聊天消息通知
 * @param sender 发送者名称
 * @param content 消息内容
 * @param avatar 发送者头像URL
 */
export function showChatNotification(sender: string, content: string, avatar?: string) {
    // 如果在免打扰模式下，不显示通知
    if (userSettings.muteNotifications) {
        return;
    }

    // 检查浏览器通知权限
    if (Notification && Notification.permission === 'granted') {
        const notification = new Notification(`新消息来自: ${sender}`, {
            body: content,
            icon: avatar || '/favicon.ico'
        });

        // 点击通知时跳转到聊天页面
        notification.onclick = () => {
            window.focus();
            window.location.href = '#/chat';
            notification.close();
        };

        // 播放消息声音
        playNotificationSound('message');
    }
    // 如果没有通知权限，使用Element Plus的消息提示
    else {
        ElMessage({
            message: `${sender}: ${content}`,
            type: 'info',
            duration: 3000
        });

        // 播放消息声音
        playNotificationSound('message');
    }
}

/**
 * 播放通知声音
 * @param type 声音类型
 */
export function playNotificationSound(type: 'message' | 'notification') {
    // 如果在静音模式下，不播放声音
    if (userSettings.muteSounds) {
        return;
    }

    const sound = notificationSounds[type];
    if (sound) {
        sound.currentTime = 0;
        sound.play().catch(err => {
            console.error('Failed to play notification sound:', err);
        });
    }
}

/**
 * 请求通知权限
 * @returns 是否获得权限
 */
export async function requestNotificationPermission(): Promise<boolean> {
    if (!('Notification' in window)) {
        console.warn('This browser does not support desktop notification');
        return false;
    }

    if (Notification.permission === 'granted') {
        return true;
    }

    if (Notification.permission !== 'denied') {
        const permission = await Notification.requestPermission();
        return permission === 'granted';
    }

    return false;
}

// 初始化通知设置
initNotificationSettings({});

export default {
    showNotification,
    showChatNotification,
    playNotificationSound,
    updateNotificationSettings,
    getNotificationSettings,
    requestNotificationPermission
}; 